package cc.rboot.inject.resolver;

import cc.rboot._core.helper.ClassHelper;
import cc.rboot.inject.annotation.InjectToken;
import cc.rboot.token.core.IToken;
import cc.rboot.token.core.ITokenAware;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.annotation.Resource;

@Component
public class InjectTokenResolver implements HandlerMethodArgumentResolver {

    @Resource
    public ITokenAware tokenAware;

    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        Class<?> parameterType = methodParameter.getParameterType();
        return ClassHelper.hasInterface(parameterType, IToken.class) && methodParameter.hasParameterAnnotation(InjectToken.class);
    }

    @Override
    public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {
        Class<? extends IToken> parameterType = (Class<? extends IToken>) methodParameter.getParameterType();
        return tokenAware.get(parameterType);
    }
}
